<template>
  <div id="app">
    <div id="container">
      <div class="left">
        <draggable v-model="draggable1" @end="end1" :options="{
            group: { name: 'site', pull: 'clone', put: false },
            sort: true,
          }" animation="300" :scroll="true" @start="start" :forceFallback="true" touchStartThreshold="300"
          dragClass="dragClass" ghostClass="ghostClass">
          <transition-group>
            <div v-for="(item, i) in selectOptions" :key="i" class="group" @dblclick="add(i)">
              <img class="icon" :src="imgs[i]" alt="" />
              {{ item.label }}
            </div>
          </transition-group>
        </draggable>

        <div @click="add()" class="group">
          <a-icon type="plus" style="padding-left:.3rem" :style="{ fontSize: '16px', color: '#1296db' }" />点击添加
        </div>
        <!-- <div @click="Check" class="group">
          校验
        </div> -->
        <!-- <a-button @click="getValues()">获取值</a-button> -->
      </div>
      <!-- 中间列表部分 -->
      <div class="center">
        <draggable ref="center" v-model="AddFromArr" :options="{ animation: 500 }" @update="datadragEnd" group="site"
          handle=".mover" :scroll="true" :forceFallback="true" dragClass="dragClass" ghostClass="ghostClass">
          <transition-group>
            <div v-for="(item, i) of AddFromArr" :key="i" class="item">
              <a-icon type="menu" style="margin-right:1rem" class="mover" />
              <span
                class="serial_number">{{ i + 1 }}\{{ AddFromArr.length }}</span><span>{{ item.formConfig.items[0].label }}</span>
              <div class="forma">
                <Questionnaire ref="form" :type="true" :formConfig="item.formConfig" class="Questionnaire">
                  <template slot="content"> </template>
                </Questionnaire>
                <div class="editBox">
                  <a-icon type="edit" @click="edit(i)" :style="{ fontSize: '16px' }" />
                  <a-icon type="delete" @click="del(i)" :style="{ fontSize: '16px' }" />
                  <!-- :style="{ fontSize: '20px', color: '#000' }" -->
                </div>
              </div>
            </div>
          </transition-group>
        </draggable>
        <div @click="add()" class="addBtn" v-if="AddFromArr.length == 0">
          <a-icon type="plus" style="padding-left:.3rem" :style="{ fontSize: '16px', color: '#1296db' }" />点击添加
        </div>
        <div class="conter-footer">
          <el-button size="medium" type="primary" @click="addVisible = true">下一步</el-button>
          <el-button size="medium">重置</el-button>
        </div>
      </div>
      <!-- 中间列表部分结束 -->
      <!-- 右边编辑部分 -->
      <div class="right">
        <div v-for="(item, i) of DditFromArr" :key="item.id" class="item">
          <span
            class="serial_number">{{ i + 1 }}\{{ AddFromArr.length }}</span><span>{{ item.formConfig.items[0].label }}</span>
          <div class="forma">
            <Questionnaire :formConfig="item.formConfig" class="Questionnaire">
              <template slot="content"> </template>
            </Questionnaire>
          </div>
        </div>
      </div>
      <a-modal title="添加题目" :visible="visible" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="handleCancel"
        ok-text="确认" cancel-text="取消">
        <a-select v-model="SelectKey" style="width: 120px" @change="handleChange">
          <a-select-option :value="item.value" v-for="(item, i) of selectOptions" :key="i">
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-modal>
    </div>

    <!-- 弹窗 -->

    <el-dialog width="900px" v-dialogDrag :visible.sync="addVisible" :close-on-click-modal="false"
      @close="addVisible = false">
      <el-form :model="addFrom" id="userDialog" status-icon :rules="addFromRules" ref="addFrom" label-position="right">
        <el-form-item label="问卷标题" prop="title" label-width="125px">
          <el-input type="text" v-model="addFrom.title" autocomplete="off" maxlength="16" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="活动主题" prop="activityName" label-width="125px">
          <el-input type="text" v-model="addFrom.activityName" autocomplete="off" maxlength="16" show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item label="活动说明" prop="activityDesc" label-width="125px">
          <el-input type="textarea" v-model="addFrom.activityDesc" autocomplete="off" maxlength="200" show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item label="顶部Banner图" prop="banner" label-width="125px">
          <div class="d-flex">
            <MyUpImg :imagePreview='addFrom.banner' imageSize="chang" @change="imageChange($event, 'banner')"></MyUpImg>
            <div class="d-flex align-center" style="margin-left:10px">
              <span style="width: 100px;">背景颜色:</span>
              <el-input type="text" v-model="addFrom.backgroundColor" autocomplete="off" maxlength="6" show-word-limit
                style="width: 180px;"></el-input>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark" label-width="125px">
          <el-input type="textarea" v-model="addFrom.remark" autocomplete="off" maxlength="200" show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFrom" size="small" :loading="btnLoading">发 布</el-button>
        <el-button @click="addVisible = false" size="small">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import Questionnaire from '@/components/Questionnaire/Questionnaire'
  import draggable from "vuedraggable"; //拖动插件
  import {
    v4
  } from "uuid";
  import {
    configFormAdd,
    configFormDetail,
    configFormEdit
  } from '@/api/getData'
  export default {
    components: {
      Questionnaire,
      draggable,
    },
    data() {
      return {
        moveId: -1,
        draggable1: [],
        btnLoading: false,
        addFrom: {
          title: '',
          activityName: '',
          activityDesc: '',
          banner: '',
          backgroundColor: '',
          remark: ''
        }, //要提交的表单
        addFromRules: {
          title: [{
            required: true,
            message: '请输入问卷标题',
            trigger: 'blur'
          }],
          remark: [{
            required: true,
            message: '请输入备注',
            trigger: 'blur'
          }],
          // expireType: [{required: true, message: '请选择领取后有效期',trigger: 'blur'}],
        },
        visible: false,
        confirmLoading: false,
        formConfig: {},
        SelectKey: 0,
        addVisible: false, //弹窗是否显示
        imgs: [
          require("../../assets/icon/radio.svg"),
          require("../../assets/icon/checkbox.svg"),
          require("../../assets/icon/subjective.svg"),
        ],
        // 格式
        selectOptions: [{
            label: "单选题",
            value: 0,
            id: v4(),
          },
          {
            label: "多选题",
            value: 1,
            id: v4(),
          },
          {
            label: "主观题",
            value: 2,
            id: v4(),
          },
        ],
        // 正则验证
        FromArr: [{
            formConfig: {
              data: {
                value: null
              },
              items: [{
                type: "radio",
                value: "",
                id: "",
                label: "单选题",
                title: "单选题", //标题
                subheading: "", //次标题
                sort: "", //排序
                prop: "value",
                // label: "检测项目",
                answerList: [{
                    value: "选项1",
                    label: "选项1"
                  },
                  {
                    value: "选项2",
                    label: "选项2"
                  },
                ],
                placeholder: "请输入题目",
              }, ],
              rules: {
                value: [{
                  required: true,
                  message: "请选择选项",
                  trigger: "change",
                }, ],
              },
            },
          },
          {
            formConfig: {
              data: {
                value: null
              },
              items: [{
                type: "checkbox",
                value: [],
                id: "",
                label: "多选题",
                title: "多选题", //标题
                subheading: "", //次标题
                sort: "", //排序
                prop: "value",
                // label: "检测项目",
                answerList: [{
                    value: "选项1",
                    label: "选项1"
                  },
                  {
                    value: "选项2",
                    label: "选项2"
                  },
                ],
                placeholder: "请输入题目",
              }, ],
              rules: {
                value: [{
                  required: true,
                  message: "请至少选择一项",
                  trigger: "change",
                }, ],
              },
            },
          },
          {
            formConfig: {
              data: {
                value: null
              },
              items: [{
                type: "text",
                value: "",
                id: "",
                label: "主观题",
                title: "主观题", //标题
                subheading: "", //次标题
                sort: "", //排序
                prop: "value",
                // label: "检测项目",
                answerList: [{
                  prompt: "提示",
                  value: "回答",
                }, ],
                placeholder: "请输入题目",
              }, ],
              rules: {
                value: [{
                  required: true,
                  message: "请认真完成填写",
                  trigger: "change",
                }, ],
              },
            },
          },
        ],
        // 中间的From
        AddFromArr: [],

        DditFromArr: [],
        FormObj: {},
        fromId: null, //表单ID

      };
    },
    mounted() {
      //为了防止火狐浏览器拖拽的时候以新标签打开，此代码真实有效
      document.body.ondrop = function(event) {
        event.preventDefault();
        event.stopPropagation();
      };
      this.fromId = this.$route.query.id;
      if (this.fromId) {
        this.getFromDetail()
      }else{
        this.AddFromArr.push(JSON.parse(JSON.stringify(this.FromArr[0])))
        this.DditFromArr.push(this.AddFromArr[0])
      }
    },
    methods: {
      // 获取详情
      getFromDetail() {
        configFormDetail(this.fromId).then(res => {
          console.log(res)
          if (res.code == 200) {
            let config = JSON.parse(res.data.config)
            console.log(config)
            config.forEach(item => {
              if (item.type == 'radio' || item.type == 'checkbox') {
                let _newItem = JSON.parse(JSON.stringify(this.FromArr[0]))
                let _list = []
                item.values.forEach(v => {
                  console.log(v)
                  _list.push({
                    label: v.label,
                    value: v.label
                  })
                })
                _newItem.formConfig.items[0].type = item.type;
                _newItem.formConfig.items[0].title = item.name;
                _newItem.formConfig.items[0].label = item.type == 'radio' ? '单选题' : '多选题';
                _newItem.formConfig.items[0].answerList = _list;
                this.AddFromArr.push(_newItem)
              } else if (item.type == 'text') {
                let _newItem = JSON.parse(JSON.stringify(this.FromArr[2]))
                _newItem.formConfig.items[0].title = item.name;
                this.AddFromArr.push(_newItem)
              }
            })
            this.DditFromArr.push(this.AddFromArr[0]);
            this.addFrom.title = res.data.title;
            this.addFrom.activityName = res.data.activityName;
            this.addFrom.activityDesc = res.data.activityDesc;
            this.addFrom.banner = res.data.banner;
            this.addFrom.backgroundColor = res.data.backgroundColor;
            this.addFrom.remark = res.data.remark;
            this.addFrom.id = res.data.id;
          }
        })
      },
      // 点击确定
      submitFrom() {
        this.$refs["addFrom"].validate((valid) => {
          let data = JSON.parse(JSON.stringify(this.addFrom));
          console.log(data)
          if (data.title == "") {
            this.$message.error('请输入问卷标题');
            return;
          } else if (data.remark == "") {
            this.$message.error('请输入备注');
            return;
          }else{
            let newArr = [];
            this.AddFromArr.forEach((item) => {
              console.log(item.formConfig.items)
              let child = item.formConfig.items[0];
              let newObj = {}
              newObj.type = child.type
              newObj.name = child.title
              if (child.type == "radio" || child.type == "checkbox") {
                let vList = []
                child.answerList.forEach((v) => {
                  vList.push({
                    "label": v.value,
                    "value": false
                  })
                })
                newObj.value = ''
                newObj.values = vList
              }
              newArr.push(newObj)
            })
            this.addFrom.config = JSON.stringify(newArr)
            this.addFrom.isTemplate = "Y";
            console.log(this.addFrom)
            if (!this.fromId) {
              configFormAdd(this.addFrom).then(res => {
                if (res.code == 200) {
                  this.$message.success(res.msg);
                  this.addVisible = false;
                }
              })
            } else {
              configFormEdit(this.addFrom).then(res => {
                if (res.code == 200) {
                  this.$message.success(res.msg);
                  this.addVisible = false;
                }
              })
            }
          }
        })

      },
      imageChange(path, name) {
        console.log(path)
        this.addFrom[name] = path
      },
      Check() {
        console.log(this.$refs.form);
        let resultArr = [];
        this.$refs.form.map((item) => {
          item.$refs.form.validate((valid, values) => {
            resultArr.push(valid);
          });
        });
        console.log(resultArr.indexOf(false));
        if (resultArr.indexOf(false) > -1) {
          this.$message.success("请认真填写调查问卷");
        }
      },
      //左边往右边拖动时的事件
      end1(e) {
        console.log(e)
        if (e.pullMode == "clone") {
          var that = this;
          this.FormObj.id = v4();
          console.log(this.FormObj);
          this.AddFromArr.splice(e.newDraggableIndex, 0, this.FormObj);
          this.changeDdit(e.newDraggableIndex);
          this.$message.success("添加成功");
        } else {
          this.$message.error("取消添加");
        }
        console.log(this.AddFromArr)
      },
      start(e) {
        this.FormObj = JSON.parse(
          JSON.stringify(this.FromArr[e.oldDraggableIndex])
        );
      },
      getdata(evt) {
        console.log(evt.draggedContext.element.text);
      },
      datadragEnd(evt) {
        evt.preventDefault();
        console.log("拖动前的索引 :" + evt.oldIndex);
        console.log("拖动后的索引 :" + evt.newIndex);
        this.changeDdit(evt.newIndex);
      },
      add(i) {
        if (i >= 0) {
          let that = this;
          setTimeout(() => {
            let obj = JSON.parse(JSON.stringify(that.FromArr[i]));
            obj.id = v4(); // 避免key重复
            that.AddFromArr.push(obj);
            that.changeDdit(i);
            that.$message.success("添加成功");
          }, 200);
          return;
        }
        this.visible = true;
      },
      edit(i) {
        this.changeDdit(i);
        this.$message.info("请右侧进行编辑");
      },
      changeDdit(i) {
        let obj = this.AddFromArr[i];
        obj.i = i;
        this.DditFromArr = [];
        this.DditFromArr.push(obj);
      },
      del(i) {
        this.AddFromArr.splice(i, 1);
        this.$message.success("删除成功");
      },
      handleChange() {},
      showModal() {
        this.visible = true;
      },
      handleOk(e) {
        let that = this;
        that.confirmLoading = true;
        setTimeout(() => {
          let obj = JSON.parse(JSON.stringify(that.FromArr[that.SelectKey]));

          obj.id = v4(); // 避免key重复
          that.AddFromArr.push(obj);
          that.changeDdit(that.AddFromArr.length - 1);
          that.visible = false;
          that.confirmLoading = false;
          that.$message.success("添加成功");
        }, 200);
      },
      handleCancel(e) {
        this.visible = false;
      },
      getValues() {
        let arr = [];
        this.AddFromArr.forEach((item) => {
          item.formConfig.items[0].value = item.formConfig.data.value;
          arr.push(item.formConfig.items);
        });
        console.log(arr);
      },
      onMove(e, originalEvent) {
        return false;
      },
    },
  };
</script>
<style lang="scss">
  #container {
    height: calc(100vh - 155px);
    width: 100%;
    display: flex;
    justify-content: center;

    .left {
      box-sizing: border-box;
      margin: 1rem;
      width: 25%;
      border-right: 1px solid #e0e0e0;
      // border-radius: 0.3rem;
      padding: 1rem;

      .icon {
        width: 1rem;
      }

      .group {
        display: flex;
        justify-content: space-around;
        border: 1px solid steelblue;
        padding: 0.5rem 3rem;
        margin: 1rem;
        border-radius: 0.3rem;
        cursor: pointer;
        user-select: none;
      }
    }

    .center {
      box-sizing: border-box;
      margin: 1rem;
      width: 50% !important;
      padding: 1rem;
      // border: 1px solid rgb(168, 172, 218);
      border-radius: 0.3rem;
      overflow-y: scroll;

      // height: 100vh;
      .item {
        position: relative;
        // width: 1000px;
        margin: 1rem 0;
      }

      .forma {
        box-sizing: border-box;
        margin: 0.5rem 0;

        .Questionnaire {
          box-sizing: border-box;
          width: 100%;
          // border: 1px solid rgb(168, 172, 218);
          // padding: 1rem;
          border-radius: 0.3rem;
          // margin: 1rem;
        }

        .editBox {
          position: absolute;
          box-sizing: border-box;
          background: #fff;
          box-shadow: 0px 0px 2px rgb(116, 53, 53);
          top: -0.5rem;
          right: 0.2rem;
          padding: 0.4rem 0.5rem;
          border-radius: 0.3rem;
          display: flex;
          justify-content: space-around;
          width: 70px;
        }
      }
    }

    .right {
      box-sizing: border-box;
      margin: 1rem;
      width: 25%;
      padding: 1rem;
      border-left: 1px solid #e0e0e0;

      .forma {
        box-sizing: border-box;
        margin: 0.5rem 0;

        .Questionnaire {
          box-sizing: border-box;
          width: 100%;
          border: 1px solid rgb(168, 172, 218);
          padding: 1rem;
          border-radius: 0.3rem;
          // margin: 1rem;
        }
      }

      // border-radius: 0.3rem;
    }
  }

  .serial_number {
    background: #e5e5e5 !important;
    padding: 0.1rem 0.5rem;
    margin-right: 0.4rem;
    border-radius: 0.2rem;
  }

  .btn {
    margin: 1rem;
  }

  .addBtn {
    width: 100%;
    display: flex;
    justify-content: center;
    padding: 0.2rem;
    border-radius: 0.2rem;
    border: 1px solid rgb(168, 172, 218);
  }
  .conter-footer{
    display: flex;
    justify-content: center;
  }
</style>
